<?php

include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class ruijie extends BaseChannel
{

    protected $appSecret;
    protected $appId;
    protected $areaMap = [
        "北京" => 1,
        "天津" => 2,
        "河北" => 3,
        "山西" => 4,
        "内蒙古" => 5,
        "辽宁" => 6,
        "吉林" => 7,
        "黑龙江" => 8,
        "上海" => 9,
        "江苏" => 10,
        "浙江" => 11,
        "安徽" => 12,
        "福建" => 13,
        "江西" => 14,
        "山东" => 15,
        "河南" => 16,
        "湖北" => 17,
        "湖南" => 18,
        "广东" => 19,
        "广西" => 20,
        "海南" => 21,
        "重庆" => 22,
        "四川" => 23,
        "贵州" => 24,
        "云南" => 25,
        "西藏" => 26,
        "陕西" => 27,
        "甘肃" => 28,
        "青海" => 29,
        "宁夏" => 30,
        "新疆" => 31,
        "台湾" => 32,
        "香港" => 33,
        "澳门" => 34,
    ];
    // protected $header = [
    //     "Content-Type:application/json"
    // ];

    public function __construct($options)
    {
        parent::__construct($options);
        $this->appSecret = $options['appSecret'];
        $this->appId = $options['appId'];
    }
    // 计算签名提单需要签名  emptyWithSign 为空参与签名
    public function getSign($data, $emptyWithSign = false)
    {
        foreach ($data as $key => $val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
        }
        $data['appSecret'] = $this->appSecret;
        ksort($data);

        $str = http_build_query($data);
        $str = urldecode($str);
        var_dump(1111);
        var_dump($str);
        $sign = (md5($str));
        return $sign;
    }
    public function queryBalance($params = [])
    {
        // return [
        //     'error' => 1,
        //     'msg' =>  '不支持查询余额',
        //     'code' => 500
        // ];
        $data['appId'] = $this->appId;

        $data['timestamp'] = date('YmdHis') * 1000;

        $data['sign'] = $this->getSign($data);
        $url = $this->query_order_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 00) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['balance'] ?? 0, //余额
                'credit' =>  0, //授信
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['msg'] ?? '查询失败',
            'code' => 500
        ];
    }
    //params :{push_order_sn:''} 
    public function queryOrder($params)
    {

        $data['appId'] = $this->appId;
        $data['outOrderId'] = $params['push_order_sn'];
        $data['timestamp'] = date('YmdHis') * 1000;

        $data['sign'] = $this->getSign($data);
        $url = $this->query_order_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' =>  '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //处理中
        // if ($return_data['resultCode'] == 1 && $return_data['chargeStatus'] == 1) {
        //     $ret['msg'] = '充值中';
        // }
        // 成功
        if ($return_data['code'] == "00" && $return_data['orderStatus'] == 2) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['msg'];
        }
        // 失败
        if ($return_data['code'] == "00" && ($return_data['orderStatus'] == 3)) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['msg'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {

        // 1:移动,2:联通,3:电信
        $data = [];
        $isp_map = [
            1 => "yd",
            2 => "lt",
            3 => "dx"
        ];
        $area = $params['area_name'];
        $areas = explode('-', $area);
        $province = $this->areaMap[$areas[0]];
        if ($params['hf_type'] == 1) {
            // 1快充2慢充
            $timeout = 60 * 24; //快充一天
        } else {
            // 慢充 默认24小时可以是倍数调整数值1即可
            $timeout = 60 * 24 * 3;
        }

        $data['appId'] = $this->appId;
        $data['outOrderId'] = $params['push_order_sn'];
        $data['itemId'] = $code;
        $data['uuid'] = $mobile;
        $data['provinceCode'] = $province;
        $data['timestamp'] = date('YmdHis') * 1000;

        $data['timeout'] = $timeout;
        $data['isp'] = $isp_map[$params['isp']];

        $data['callbackUrl'] = $this->callback_url;

        $data['sign'] = $this->getSign($data);

        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $this->submit_order_url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['orderId'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  $return_data['cost'] ?? null,
            'channel_balance' => null,
        ];
        if ($return_data['code'] == "00") {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = $params['orderId'];
        $this->push_order_sn = $params['outOrderId'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['orderStatus'];
        $msg = $params['orderDesc'];
        //凭证
        $pz =  $params['ext1'] ?? '';
        $res['voucher'] = $pz;
        // 验证签名
        $sign = $this->getSign($params);

        if ($sign !== $params['sign']) {
            $res['error'] = 1;
            $res['msg'] = '签名不匹配';
            $res['resp_data'] = 'fail';
            $res['sign'] = $sign;
            return $res;
        }
        if ($order_status == 2) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'success';
        }
        if ($order_status == 3) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
            $res['resp_data'] = 'success';
        }
        //初始化就是充值中
        // if ($order_status == 10) {
        //     $res['order_status'] = 2;
        //     $res['msg'] = $msg ?? '充值中';
        // }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
    public function getAreaCode($province)
    {
        $map = [
            "北京" => 110000,
            "天津" => 120000,
            "河北" => 130000,
            "山西" => 140000,
            "内蒙古" => 150000,
            "辽宁" => 210000,
            "吉林" => 220000,
            "黑龙江" => 230000,
            "上海" => 310000,
            "江苏" => 320000,
            "浙江" => 330000,
            "安徽" => 340000,
            "福建" => 350000,
            "江西" => 360000,
            "山东" => 370000,
            "河南" => 410000,
            "湖北" => 420000,
            "湖南" => 430000,
            "广东" => 440000,
            "广西" => 450000,
            "海南" => 460000,
            "重庆" => 500000,
            "四川" => 510000,
            "贵州" => 520000,
            "云南" => 530000,
            "西藏" => 540000,
            "陕西" => 610000,
            "甘肃" => 620000,
            "青海" => 630000,
            "宁夏" => 640000,
            "新疆" => 650000
        ];
        return $map[$province];
    }
}
